import os
import json
import threading
from datetime import datetime

from numpy.core.records import record

emotion_keywords_file = "data/emotion_keywords.json"

record_local_file = "record.md"

class EmoAnal:
    def __init__(self, keywords_file=emotion_keywords_file, record_file=record_local_file):
        self.keywords_n, self.keywords_p = self._load_keywords(keywords_file)
        self.record_file = record_file
        self.last_status = None
        self.file_lock = threading.Lock()

    @staticmethod
    def _load_keywords(file_path):
        """从JSON文件加载关键词"""
        negative_keywords = []
        positive_keywords = []

        if os.path.exists(file_path):
            try:
                with open(file_path, 'r', encoding='utf-8') as file:
                    keywords_data = json.load(file)
                    negative_keywords = keywords_data.get("negative", [])
                    positive_keywords = keywords_data.get("positive", [])
            except json.JSONDecodeError:
                print(f"警告：JSON文件格式错误: {file_path}")
            except Exception as e:
                print(f"加载关键词文件时出错: {e}")
        else:
            print(f"警告：关键词文件不存在: {file_path}")

        return negative_keywords, positive_keywords

    def check_keywords(self, input_text):
        """检查输入文本中的关键词，返回当前心情状态"""
        current_status = None

        # 检查是否包含负向关键词
        for keyword in self.keywords_n:
            if keyword in input_text:
                current_status = "当前状态 : 😢"
                break

        # 检查是否包含正向关键词
        if current_status is None:
            for keyword in self.keywords_p:
                if keyword in input_text:
                    current_status = "当前状态 : 😊"
                    break

        # 默认状态
        if current_status is None:
            current_status = "当前状态 : 😐"

        # 如果状态发生变化，记录到文件
        if current_status != self.last_status:
            self.last_status = current_status
            self._write_to_record(current_status, input_text)

        return current_status

    def _write_to_record(self, status, text):
        """将状态变化写入记录文件"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # 格式化记录内容，消极记录加粗
        if "😢" in status:
            formatted_status = f"**{status}**"
        else:
            formatted_status = status

        record_line = f"[{timestamp}] {formatted_status} - 用户输入: {text}\n"

        with self.file_lock:
            with open(self.record_file, 'a', encoding='utf-8') as f:
                f.write(record_line)


EmotionAnalysis = EmoAnal